/**
 * Created by PanJiaChen on 16/11/18.
 */
const Base64 = require('js-base64').Base64;
/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, ' ') +
      '"}'
  )
}

// getDuration 毫秒转换为s、min、h
export function getDuration(msd) {
  let time = parseFloat(msd) / 1000 // 先将毫秒转化成秒
  if (time != null && time !== '') {
    if (time > 60 && time < 60 * 60) {
      time = parseInt(time / 60.0) + '分' + parseInt((parseFloat(time / 60.0) -
        parseInt(time / 60.0)) * 60) + '秒'
    } else if (time >= 60 * 60 && time < 60 * 60 * 24) {
      time = parseInt(time / 3600.0) + '小时' + parseInt((parseFloat(time / 3600.0) -
        parseInt(time / 3600.0)) * 60) + '分' +
        parseInt((parseFloat((parseFloat(time / 3600.0) - parseInt(time / 3600.0)) * 60) -
          parseInt((parseFloat(time / 3600.0) - parseInt(time / 3600.0)) * 60)) * 60) + '秒'
    } else {
      time = parseInt(time) + '秒'
    }
  }
  return time
}

export function handleTimeDuration(times) {
  var minute = 1000 * 60
  var hour = minute * 60
  var day = hour * 24
  var week = day * 7
  var month = day * 30

  var time1 = new Date().getTime()// 当前的时间戳
  var time2 = Date.parse(new Date(parseTime(times)))// 指定时间的时间戳
  var time = time1 - time2
  var result = null
  if (time < 0) {
    alert('设置的时间不能早于当前时间！')
  } else if (time / month >= 1) {
    result = parseInt(time / month) + '月前'
  } else if (time / week >= 1) {
    result = parseInt(time / week) + '周前'
  } else if (time / day >= 1) {
    result = parseInt(time / day) + '天前'
  } else if (time / hour >= 1) {
    result = parseInt(time / hour) + '小时前'
  } else if (time / minute >= 1) {
    result = parseInt(time / minute) + '分钟前'
  } else {
    result = '刚刚'
  }
  return result
}

/**
 * @description: base64解析
 * @param {String} 
 * @return {Object} 
 */
export function base64Parse(data, defaultValue = []) {
  if (typeof data === 'string') {
    try {
      data = JSON.parse(Base64.decode(data))
    } catch (error) {
      return defaultValue
    }
    if (typeof data === 'string') {
      return base64Parse(data, defaultValue)
    } else {
      return data || defaultValue
    }
  } else {
    return data || defaultValue
  }
}

/**
 * @description: 浮点数减法
 * @param {type} 
 * @return {type} 
 */
export const minus = (num1, num2) => {
  const num1Digits = (num1.toString().split('.')[1] || '').length
  const num2Digits = (num2.toString().split('.')[1] || '').length
  const baseNum = Math.pow(10, Math.max(num1Digits, num2Digits))
  return (times(num1, baseNum) - times(num2, baseNum)) / baseNum
}

function times(num1, num2) {
  const num1String = num1.toString()
  const num2String = num2.toString()
  const num1Digits = (num1String.split('.')[1] || '').length
  const num2Digits = (num2String.split('.')[1] || '').length
  const baseNum =  Math.pow(10, num1Digits + num2Digits)
  return Number(num1String.replace('.', '')) * Number(num2String.replace('.', '')) / baseNum
}
